import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { MenuService } from './menu/menu.service';

@Injectable({
  providedIn: 'root'
})
export class CanActivateGuard implements CanActivate {
  constructor(private router: Router, private menuService: MenuService) {}
  private whitelistUrls: RegExp[] = [
    /^\/pages\/basicdata\/userCenter(\/.*)?$/,
    /^\/pages\/basicdata\/userCenter\/[^\/]+\/[^\/]+$/,
    /^\/pages\/basicdata\/userCenter\/[^\/]+\/[^\/]+\/[^\/]+$/,// 新的 URL 模式
    /^\/opterator-tasks\/opterator-task-datail(\?.*)?$/, // 添加新的白名单 URL，匹配带有查询参数的 URL
    /^\/pages\/inventory\/returning-materials-detail(\/.*)?$/,
    /^\/pages\/product\/lrp(\/.*)?$/,
    /^\/pages\/product\/add-lrp(\/.*)?$/,
    /^\/pages\/product\/edit-lrp(\/.*)?$/,
    /^\/pages\/purchase\/purchase-payment(\/.*)?$/,
    /^\/pages\/purchase\/purchase-payment(\/.*)?$/,
     /^\/pages\/purchase\/purchase-ledger(\/.*)?$/,
    /^\/pages\/purchase\/add-purchase-payment(\/.*)?$/,
    /^\/pages\/purchase\/ingredient-reimbursement-approval-add(\/.*)?$/,
    /^\/pages\/basicdata\/wuliuguanli(\/.*)?$/,
    /^\/pages\/sales-master\/sales-ledger(\/.*)?$/,
     /^\/pages\/sales-master\/after-sales-center(\/.*)?$/,
    /^\/pages\/sales-master\/sales-payment(\/.*)?$/,
    /^\/pages\/sales-master\/add-sales-payment(\/.*)?$/,
    /^\/pages\/inventory\/other-indevntory(\/.*)?$/,
    /^\/pages\/inventory\/other-outbound(\/.*)?$/,
    /^\/pages\/inventory\/inventory-warning(\/.*)?$/,
    /^\/pages\/purchase\/ingredient-purchase-request(\/.*)?$/,
    /^\/pages\/purchase\/ingredient-purchase-request-add(\/.*)?$/,
    /^\/pages\/purchase\/ingredient-reimbursement-approval(\/.*)?$/,
  ];
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    const userInfo = localStorage.getItem('userinfo') || sessionStorage.getItem('userinfo');
    const url = state.url; // 获取当前导航的URL
    const routeParams = route.params; // 获取路由参数
    // 如果是403页面，直接允许访问
    if (url === '/pages/abnormal/abnormal403') {
      return true;
    }
    if (userInfo) {
      if (this.whitelistUrls.some(pattern => pattern.test(url))) {
        return true;
      }
      if (url === '/' || url === '/pages') {
        const firstMenuItemUrl = this.getFirstMenuItemUrl();
        console.log(firstMenuItemUrl);
        if (firstMenuItemUrl) {
          this.router.navigate([firstMenuItemUrl]);
          return false;
        }
      }
      if (this.hasMenuItems(url, routeParams)) {
        return true;
      } else {
        this.router.navigate(['/pages/abnormal/abnormal403']); // 无权限跳转到403页面
        return false;
      }
    } else {
      this.router.navigate(['/login']); // 未登录跳转到登录页面
      return false;
    }
  }
  hasMenuItems(url: string, params: any): boolean {
    const menuItems = this.menuService.getMenuItems(); // 从 MenuService 获取菜单项
    return this.checkMenuItems(menuItems, url, params);
  }

  private checkMenuItems(menuItems: any[], url: string, params: any): boolean {
    // 移除 URL 中的查询参数部分
    const [cleanUrl, queryParams] = url.split('?');
    const prefixedUrl = cleanUrl.startsWith('/pages') ? cleanUrl : `/pages${cleanUrl}`;

    for (const item of menuItems) {
      if (item.link) {
        // 将 item.link 中的查询参数形式转换为路径参数形式
        const itemLinkPattern = item.link.replace(/\?id=:[^/]+/, '/:id').replace(/:[^/]+/g, '[^/]+');
        const itemLinkRegex = new RegExp(`^${itemLinkPattern}$`);
        if (itemLinkRegex.test(cleanUrl) || itemLinkRegex.test(prefixedUrl)) {
          return true;
        }
      }
      if (item.childrenMenu && item.childrenMenu.length > 0) {
        if (this.checkMenuItems(item.childrenMenu, cleanUrl, params)) {
          return true;
        }
      }
    }
    return false;
}

  private getFirstMenuItemUrl(): string | null {
    const menuItems = this.menuService.getMenuItems(); // 从 MenuService 获取菜单项
    for (const item of menuItems) {
      if (item.link) {
        return item.link;
      }
      if (item.childrenMenu && item.childrenMenu.length > 0) {
        const childLink = this.getFirstMenuItemUrlFromChildren(item.childrenMenu);
        if (childLink) {
          return childLink;
        }
      }
    }
    return null;
  }

  private getFirstMenuItemUrlFromChildren(childrenMenu: any[]): string | null {
    for (const item of childrenMenu) {
      if (item.link) {
        return item.link;
      }
      if (item.childrenMenu && item.childrenMenu.length > 0) {
        const childLink = this.getFirstMenuItemUrlFromChildren(item.childrenMenu);
        if (childLink) {
          return childLink;
        }
      }
    }
    return null;
  }
}
